package tree.medium;

import tree.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

public class EvenOddTree_1609 {

    public boolean isEvenOddTree(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean rule = true;

        while (!queue.isEmpty()) {

            int size = queue.size(), prev = rule ? 0 : Integer.MAX_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (rule && (poll.val % 2 == 0 || prev >= poll.val))
                    return false;
                if (!rule && (poll.val % 2 != 0 || prev <= poll.val))
                    return false;
                if (poll.left != null)
                    queue.offer(poll.left);
                if (poll.right != null)
                    queue.offer(poll.right);
                prev = poll.val;
            }
            rule = !rule;
        }
        return true;
    }

}
